import React, { useState, useEffect, useRef } from "react";
import PropTypes from "prop-types";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faSearch, faTimes } from "@fortawesome/free-solid-svg-icons";
import useKeyPress from "../hooks/useKeyPress";
import useIpcRender from "../hooks/useIpcRender";

const FileSearch = ({ title, onSearch }) => {
  const [isActive, setIsActive] = useState(false);
  const [inputValue, setInputValue] = useState("");
  let node = useRef(null);

  const pressEnter = useKeyPress(13);
  const pressEsc = useKeyPress(27);

  const resetInput = () => {
    setIsActive(false);
    setInputValue("");
    onSearch("");
  };

  useEffect(() => {
    const handlePressKey = (e) => {
      if (isActive && pressEnter) {
        onSearch(inputValue);
      }
      if (isActive && pressEsc) {
        resetInput();
      }
    };
    window.addEventListener("keyup", handlePressKey);
    return () => {
      window.removeEventListener("keyup", handlePressKey);
    };
  });

  useEffect(() => {
    if (isActive) {
      node.current.focus();
    }
  }, [isActive]);

  useIpcRender({
    "search-file": () => {
      setIsActive(true);
    },
  });

  return (
    <div className="alert alert-primary d-flex justify-content-between align-items-center mb-0 file-serach">
      {!isActive && (
        <>
          <span>{title}</span>
          <button
            type="button"
            className="icon-btn"
            onClick={() => setIsActive(true)}
          >
            <FontAwesomeIcon title="搜索" icon={faSearch} />
          </button>
        </>
      )}
      {isActive && (
        <>
          <input
            className="form-control form-control-sm"
            value={inputValue}
            ref={node}
            onChange={(e) => {
              setInputValue(e.target.value);
            }}
          />
          <button className="icon-btn" type="button" onClick={resetInput}>
            <FontAwesomeIcon title="取消" icon={faTimes} />
          </button>
        </>
      )}
    </div>
  );
};

FileSearch.propTypes = {
  title: PropTypes.string,
  onSearch: PropTypes.func.isRequired,
};
FileSearch.defaultProps = {
  title: "我的文档",
};

export default FileSearch;
